<template>
  <div class="record-container">
    <!-- 左侧模型导航区 -->
    <el-aside class="model-aside" width="360px">
      <el-menu
          :default-active="selectIndex.toString()"
          class="aside-menu"
          @select="selectModel"
          active-text-color="#409EFF"
      >
        <el-menu-item index="1">
          <el-icon><Menu /></el-icon>
          <span>全局模型</span>
        </el-menu-item>
        <el-menu-item index="2">
          <el-icon><user /></el-icon>
          <span>我的模型</span>
        </el-menu-item>
      </el-menu>

      <!-- 模型列表 -->
      <el-scrollbar class="model-list" >
        <div v-if="selectIndex === '1'" class="model-group">
          <el-card
              v-for="item in modelList"
              :key="item.id"
              class="model-card"
              shadow="hover"
              @click="modelRecordFun(item)"
          >
            <div class="model-header">
              <span class="model-name">{{ item.name }}</span>
              <el-tag type="info" size="small">{{ item.unitCn }}</el-tag>
            </div>
            <div class="model-meta">
              <span class="unit">{{ item.unit }}</span>
              <span class="value-range">正常范围: {{ item.minValue }}-{{ item.maxValue }}</span>
            </div>
          </el-card>
        </div>

        <div v-if="selectIndex === '2'" class="model-group">
          <el-button
              type="primary"
              class="add-btn"
              @click="dialogAddModel = true"
          >
            <el-icon><plus /></el-icon>
            新建模型
          </el-button>

          <el-card
              v-for="item in myModelList"
              :key="item.id"
              class="model-card"
              shadow="hover"
              @click="modelRecordFun(item)"
          >
            <div class="model-header">
              <span class="model-name">{{ item.name }}</span>
              <div class="actions">
                <el-button
                    type="danger"
                    size="small"
                    @click.stop="deleteModel(item.id)"
                >
                  删除
                </el-button>
              </div>
            </div>
            <div class="model-meta">
              <el-tag type="info" size="small">{{ item.unitCn }}</el-tag>
              <span class="unit">{{ item.unit }}</span>
              <span class="value-range">输入限制: {{ item.minInput }}-{{ item.maxInput }}</span>
            </div>
          </el-card>
        </div>
      </el-scrollbar>
    </el-aside>

    <!-- 右侧数据录入区 -->
    <el-main class="record-main">
      <el-card class="input-panel" shadow="never">
        <template #header>
          <div class="panel-header">
            <h2>数据录入面板</h2>
            <el-tag v-if="modelRecord.name" type="success">当前模型: {{ modelRecord.name }}</el-tag>
          </div>
        </template>

        <el-empty v-if="modelRecord.name==null" description="选择左侧模型开始记录" />

        <el-form
            v-else
            :model="modelRecord"
            label-width="120px"
            label-position="left"
            class="record-form"
        >
          <el-form-item label="模型数值">
            <el-input-number
                v-model="modelRecord.record"
                :min="modelRecord.minInput"
                :max="modelRecord.maxInput"
                :step="1"
                controls-position="right"
                style="width: 240px"
            />
            <div class="input-tip">
              正常范围: {{ modelRecord.minValue }} ~ {{ modelRecord.maxValue }}
            </div>
          </el-form-item>

          <el-form-item label="记录时间">
            <el-date-picker
                v-model="modelRecord.createTime"
                type="datetime"
                placeholder="选择记录时间"
                :default-value="new Date()"
                :shortcuts="timeShortcuts"
            />
          </el-form-item>

          <el-form-item>
            <el-button
                type="primary"
                size="large"
                @click="addModelRecord"
            >
              <el-icon><check /></el-icon>
              提交记录
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-main>

    <!-- 新增模型对话框 -->
    <el-dialog
        v-model="dialogAddModel"
        title="新建健康模型"
        width="600px"
        center
    >
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          label-position="left"
      >
        <el-form-item label="模型名称" prop="name" required>
          <el-input v-model="form.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="单位英文" prop="unit" required>
          <el-input v-model="form.unit" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="单位中文">
          <el-input v-model="form.unitCn" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="正常范围" required>
          <div style="display: flex">
            <el-input v-model="form.minValue" autocomplete="off" style="width:80px" placeholder="最小值"/>
            --
            <el-input v-model="form.maxValue" autocomplete="off" style="width:80px" placeholder="最大值"/>
          </div>
        </el-form-item>
        <el-form-item label="限制输入范围" required>
          <div style="display: flex">
            <el-input v-model="form.minInput" autocomplete="off" style="width:80px" placeholder="最小值"/>
            --
            <el-input v-model="form.maxInput" autocomplete="off" style="width:80px" placeholder="最大值"/>
          </div>
        </el-form-item>
        <el-form-item label="简介">
          <el-input type="textarea" v-model="form.note" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="addModel">确认创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>

import {onMounted, ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {addModelApi, addModelRecordApi, deleteModelApi, getMyModelApi} from "@/api/model.js";
import router from "@/router/index.js";
import {intAreaAuth, intAuth, loginAuth} from "@/tool/commonFun.js";
import {Check, Menu, Plus, User} from "@element-plus/icons-vue";

// 新增时间快捷选项
const timeShortcuts = [
  {
    text: '当前时间',
    value: new Date(),
  },
  {
    text: '一小时前',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000)
      return date
    },
  },
]

const selectIndex = ref(1)
//全局模型
const modelList = ref([])
//我的模型
const myModelList = ref([])
//记录模型
const modelRecord = ref({id: null, name: null, record: null, createTime: null, minInput: null, maxInput: null})

//打开新增模型对话框
const dialogAddModel = ref(false)
//对话框表单
const form = ref({
  name: null,
  note: null,
  maxValue: null,
  minValue: null,
  createTime: null,
})
//表单校验
const rules = {
  name: [{required: true, message: '请输入模型名称', trigger: 'blur'}],
  unit: [{required: true, message: '请输入单位英文', trigger: 'blur'}],
}
const formRef = ref(null)

//开局初始化数据
onMounted(() => {
  initData()
})

function initData() {
  getGlobelModel()
  if (loginAuth() == 0) {
    return
  }
  getMyModel()
}

function getGlobelModel() {
  getMyModelApi("0").then(res => {
    modelList.value = res.data
  })
}

//获取我的模型
function getMyModel() {
  getMyModelApi("1").then(res => {
    myModelList.value = res.data
  })
}

//选择模型类型
function selectModel(index) {
  selectIndex.value = index
}

//选择要记录的模型
function modelRecordFun(item) {
  modelRecord.value.id = item.id
  modelRecord.value.name = item.name
  modelRecord.value.minValue = Number(item.minValue)
  modelRecord.value.maxValue = Number(item.maxValue)
  modelRecord.value.minInput = Number(item.minInput)
  modelRecord.value.maxInput = Number(item.maxInput)
  modelRecord.value.unit = item.unit
}

//输入框文字计算
function area(min, max) {
  return "正常值范围：" + min + "~" + max
}

//上传模型
function addModel() {
  let max, min, maxInput, minInput
  max = intAuth(form.value.maxValue)
  min = intAuth(form.value.minValue)
  maxInput = intAuth(form.value.maxInput)
  minInput = intAuth(form.value.minInput)
  if (max < min) {
    return ElMessage({message: '最大值不能小于最小值', type: 'error'})
  }
  if (maxInput < minInput) {
    return ElMessage({message: '限制最大值不能小于最小值', type: 'error'})
  }
  if (max > maxInput || max < minInput || min > maxInput || min < minInput) {
    return ElMessage({message: '正常范围不在限制输入范围之内', type: 'error'})
  }
  form.value.maxValue = max
  form.value.minValue = min
  form.value.maxInput = maxInput
  form.value.minInput = minInput
  formRef.value.validate((valid) => {
    if (valid) {
      addModelApi(form.value).then(res => {
        ElMessage({message: res.msg, type: 'success'})
        dialogAddModel.value = false
        getMyModel()
      })
    } else {
      ElMessage({message: '验证sb', type: 'error'})
    }
  })
}

//上传模型记录
function addModelRecord() {
  let a = intAuth(modelRecord.value.record)
  let b = intAuth(modelRecord.value.minInput)
  let c = intAuth(modelRecord.value.maxInput)
  let number = intAreaAuth(a, b, c)
  if (modelRecord.value.createTime > new Date()) {
    return ElMessage({message: '时间不能大于当前时间', type: 'error'})
  }
  const data = {
    modelId: modelRecord.value.id,
    value: modelRecord.value.record,
    createTime: modelRecord.value.createTime,
  }
  addModelRecordApi(data).then(res => {
    ElMessage({message: res.msg, type: 'success'})
    router.push({path: '/health/model'})
  })
}

//删除模型
function deleteModel(id) {
  ElMessageBox.confirm(
      '你想要删除这个模型吗?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    deleteModelApi(id).then(res => {
      ElMessage({message: res.msg, type: 'success'})
      getMyModel()
      modelRecord.value.name = null
    })
  })
}

//取消按钮
function cancel() {
  reset()
  dialogAddModel.value = false
}

//表单重置
function reset() {
  form.value.name = null
  form.value.note = null
  form.value.unit = null
  form.value.unitCn = null
  form.value.maxValue = null
  form.value.minValue = null
}

</script>

<style scoped lang="scss">
.record-container {
  display: flex;
  height: calc(100vh - 80px);
  background: #f5f7fa;

  .model-aside {
    border-right: 1px solid #ebeef5;
    background: white;

    .aside-menu {
      border-right: none;
      padding: 0 20px;
    }

    .model-list {
      padding: 0 20px;

      .model-group {
        display: flex;
        flex-direction: column;
        gap: 12px;

        .add-btn {
          width: 100%;
          margin-bottom: 16px;
        }

        .model-card {
          cursor: pointer;
          transition: transform 0.2s;

          &:hover {
            transform: translateX(4px);
          }

          .model-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;

            .model-name {
              font-size: 16px;
              font-weight: 500;
            }
          }

          .model-meta {
            display: flex;
            align-items: center;
            gap: 8px;
            color: #909399;
            font-size: 13px;
          }
        }
      }
    }
  }

  .record-main {
    padding: 24px;

    .input-panel {
      height: 100%;
      background: white;

      .panel-header {
        display: flex;
        align-items: center;
        justify-content: space-between;

        h2 {
          margin: 0;
          color: #303133;
        }
      }

      .record-form {
        max-width: 600px;
        margin-top: 40px;

        .input-tip {
          color: #909399;
          font-size: 12px;
          margin-top: 8px;
        }
      }
    }
  }
}
</style>